package com.meitianhui.convenitenbuy.module.store.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.reflect.TypeToken;
import com.meitianhui.convenitenbuy.App;
import com.meitianhui.convenitenbuy.Constants;
import com.meitianhui.convenitenbuy.R;
import com.meitianhui.convenitenbuy.base.BaseToolbarActivity;
import com.meitianhui.convenitenbuy.config.InfoProvider;
import com.meitianhui.convenitenbuy.module.store.adapter.PreferentialActivityAdapter;
import com.meitianhui.convenitenbuy.module.store.contract.PreferentialActivityContract;
import com.meitianhui.convenitenbuy.module.store.di.DaggerStoreComponent;
import com.meitianhui.convenitenbuy.module.store.di.StoreModule;
import com.meitianhui.convenitenbuy.module.store.model.CouponCardInfo;
import com.meitianhui.convenitenbuy.module.store.presenter.PreferentialActivityPresenter;
import com.meitianhui.convenitenbuy.module.wallet.model.PayResultBean;
import com.meitianhui.convenitenbuy.module.wallet.ui.activity.WalletCouponActivity;
import com.meitianhui.convenitenbuy.util.GsonParserUtils;
import com.meitianhui.convenitenbuy.util.JumpUtil;
import com.meitianhui.convenitenbuy.util.RxBus;
import com.meitianhui.convenitenbuy.util.TipUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.inject.Inject;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * Created by Administrator on 2017/11/27.
 */

public class PreferentialActivityActivity extends BaseToolbarActivity
        implements PreferentialActivityContract.View {

    private RecyclerView mRecyclerView;
    private View mNotDataView;
    private TextView mTvContent;
    private String mStoreId, mStoreName, mStoreAddress, mPicInfo;
    private List<CouponCardInfo.Coupon> couponList = new ArrayList<>();
    private HashMap<String, String> mUrlMap = new HashMap<>();
    private PreferentialActivityAdapter mAdapter;
    @Inject
    PreferentialActivityPresenter presenter;

    @Override
    protected int setView() {
        return R.layout.activity_preferential_activity;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        DaggerStoreComponent
                .builder()
                .appComponent(App.getInstance().getAppComponent())
                .storeModule(new StoreModule(this))
                .build()
                .inject(this);
        mRecyclerView = getViewById(R.id.recycler_view);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);
        mNotDataView = getLayoutInflater().inflate(R.layout.data_empty_goods, (ViewGroup) mRecyclerView.getParent(), false);
        mTvContent = (TextView) mNotDataView.findViewById(R.id.tv_content);
        mTvContent.setText("暂无优惠活动");
        pushPayResult();
        initData();
    }

    private void initData() {
        setTbTitle("优惠活动");
        setTbMenu(R.mipmap.icon_title_coupon);
        mStoreId = getIntent().getStringExtra("store_id");
        mStoreName = getIntent().getStringExtra("store_name");
        mStoreAddress = getIntent().getStringExtra("store_address");
        mPicInfo = getIntent().getStringExtra("pic_info");
        mUrlMap = (HashMap<String, String>) getIntent().getSerializableExtra("url_map");
        presenter.getCouponCard(mStoreId);
        mAdapter = new PreferentialActivityAdapter(couponList);
        mRecyclerView.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (couponList.get(position).Type == 0) {
                    Intent intent = new Intent(PreferentialActivityActivity.this, PreferentialDetailActivity.class);
                    CouponCardInfo.Coupon coupon = couponList.get(position);
                    String sNum = coupon.getUsable_num();//可用数量
                    if (!sNum.equals("") || sNum != null) {
                        Integer num = Integer.parseInt(sNum);
                        if (num <= 0) {//已领光
                            TipUtils.showToast(App.getInstance(), "已领光");
                            return;
                        }
                        intent.putExtra("store_id", mStoreId);
                        intent.putExtra("store_name", mStoreName);
                        intent.putExtra("store_address", mStoreAddress);
                        intent.putExtra("coupon", coupon);//优惠券商品分类 1现金购买 2礼券对话 3免费领取
                        startActivity(intent);
                    }
                }
            }
        });
    }

    @Override
    protected void clickMenu() {
        super.clickMenu();
        if (!InfoProvider.getLoginStatus(this)) {
            JumpUtil.jumpToLoginActivity(0, PreferentialActivityActivity.this, 0, "");
            return;
        }
        Intent intent = new Intent(PreferentialActivityActivity.this, WalletCouponActivity.class);
        startActivity(intent);
    }

    @Override
    public void getCouponCardSuccess(CouponCardInfo data) {
        couponList.clear();
        refreshFinish();
        for (int i = 0; i < data.getList().size(); i++) {
            data.getList().get(i).Type = 0;
            if (data.getDoc_url() != null) {
                mUrlMap.putAll(data.getDoc_url());
            }
            couponList.add(data.getList().get(i));
        }
        TypeToken<List<CouponCardInfo.Coupon>> token = new TypeToken<List<CouponCardInfo.Coupon>>() {
        };
        try {
            List<CouponCardInfo.Coupon> list = GsonParserUtils.getInstance().fromJson(mPicInfo, token);
            for (int i = list.size() - 1; i >= 0; i--) {
                list.get(i).Type = 1;
                if (TextUtils.isEmpty(list.get(i).getPath_id())) {
                    list.remove(i);
                }
            }
            couponList.addAll(list);
        } catch (Exception e) {
            e.printStackTrace();
        }
        final int size = couponList == null ? 0 : couponList.size();
        mAdapter.setNewData(couponList, mUrlMap);
        if (size == 0) {
            mAdapter.setEmptyView(mNotDataView);
        }

    }

    private void pushPayResult() {
        Disposable disposable = RxBus.get().toFlowable(PayResultBean.class).subscribe(new Consumer<PayResultBean>() {
            @Override
            public void accept(PayResultBean payResultBean) throws Exception {
                if (payResultBean != null) {
                    if (payResultBean.result == Constants.PAY_RESULT_SUCCESS) {
                        presenter.getCouponCard(mStoreId);
                    }
                }
            }
        });
        mCompositeDisposable.add(disposable);
    }

    @Override
    protected void onRefreshData() {
        presenter.getCouponCard(mStoreId);
    }

    @Override
    public void showError(String msg) {

    }


}
